import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
// import 'package:euromillions/tools/EJ_ballsView.dart';
// import 'package:euromillions/tools/EJ_config.dart';
// import 'package:euromillions/tools/EJ_emsBalls.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
// import 'package:kerala_lottery/tools/KL_Generator.dart';

import '../Home/views/EJ_Generator_HomgPage.dart';
import '../tools/KL_Generator.dart';
import '../tools/KaL_Config.dart';
import '../tools/FL_CustomLoading.dart';
import '../tools/FL_NumberGenerator.dart';
import '../tools/FL_emsBalls.dart';
import '../tools/KaL_drawNumbersView.dart';
import '../tools/models/KL_keralaLottoDataModel.dart';
import '../tools/sqLite/EJ_myTicketEntity.dart';
import 'EJ_generaAnalyticsView.dart';
// import '../tools/sqLite/EJ_myTicketEntity.dart';
// import 'EJ_generaAnalyticsView.dart';

class EJGeneratorPageVC extends StatefulWidget {
  const EJGeneratorPageVC({super.key});

  @override
  State<EJGeneratorPageVC> createState() => _EJGeneratorPageVCState();
}

class _EJGeneratorPageVCState extends State<EJGeneratorPageVC> {
  ///保存选号到数据库
  MyTicketEntity ticketEntity = MyTicketEntity.instan();
  var _chooseNumbers = []; //要保存的号码详细信息
  int _scoredForNumbers = 0;

  var _numbers = []; //生成的号码-->int
  var _balls = []; //生成的号码-->Widget

  ///
  var _numbersMap = {};
  late List<String> _saveNumbers = []; //生成的号码-->string

  _setChooseNumbers(List numbers) {
    if (numbers.isNotEmpty) {
      _chooseNumbers.clear();
      for (var i = 0; i < numbers.length; i++) {
        var numMap = numbers[i];
        var num = numMap['number'];
        bool isregular = numMap['isRegular'];
        var number = {
          "redBall": 1,
          "number": num,
          "isRightNum": 0,
          "regularnumber": 1,
          "hasBorder": 1
        };
        if (!isregular) {
          number = {
            "redBall": 0,
            "number": num,
            "isRightNum": 0,
            "regularnumber": 0,
            "hasBorder": 1
          };
        }
        // if (i >= numbers.length - 1) {
        //   var numMap = numbers[i];
        //   var num = numMap['number'];
        // number = {
        //   "redBall": 0,
        //   "number": num,
        //   "isRightNum": 0,
        //   "regularnumber": 0,
        //   "hasBorder": 1
        // };
        // }
        _chooseNumbers.add(number);
      }
    }
  }

  ///save to checker
  _EJ_saveTpChecker() async {
    BotToast.showCustomLoading(toastBuilder: (cancelFunc) {
      return FLCustomLoading();
    });

    if (_saveNumbers.isEmpty) {
      BotToast.closeAllLoading();
      return;
    }
    // 获取当前时间戳（毫秒）
    int currentTimeMillis = DateTime.now().millisecondsSinceEpoch;
    var tickets = {
      "name": "Lucky Number",
      "time": currentTimeMillis,
      "numbers": jsonEncode(_saveNumbers),
    };

    ///保存选号
    // int save = await ticketEntity.insert(tickets);
    await ticketEntity.insert(tickets);
    Future.delayed(const Duration(seconds: 1), () {
      BotToast.closeAllLoading();
      BotToast.showText(text: 'Save successfully!');
    });
  }

  ///
  _getGeneratorNumber() {
    ///
    _scoredForNumbers = KL_Generator.instance.scoredForNumbers;

    ///
    String finalNumber = KL_Generator.instance.finalNumber;

    ///
    List<String> charArray = finalNumber.split('');
    _saveNumbers = charArray;

    List balls = [];
    // numbersMap = charArray;
    for (var i = 0; i < charArray.length; i++) {
      var ball = {
        'number': charArray[i],
        'isRight': false,
        'isNormal': true
      }; //isNormal代表是否对比中奖号码，true不用对比，false需要对比。isRight代表是否中奖号码
      balls.add(ball);
    }
    _numbersMap = {'title': '', 'balls': balls};

    setState(() {});
  }

  ///随机生成号码
  _generateRandomNumbers() async {
    BotToast.showCustomLoading(toastBuilder: (cancelFunc) {
      return FLCustomLoading();
    });
    // _balls.clear();
    // _numbers.clear();
    _saveNumbers.clear();

    // await FLNumberGenerator.instance.generateNumbers();
    await KL_Generator.instance.generateNumbers(
        KL_keralaLottoDataModel().nextDrawnModel.ticket_prefix);
    _getGeneratorNumber();

    Future.delayed(const Duration(seconds: 1), () {
      BotToast.closeAllLoading();
    });
    // setState(() {});
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _getGeneratorNumber();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Image.asset(
          'assets/sys_imgs/DearLottery Logo.png',
          width: 160,
          height: 50,
        ),
        backgroundColor: Colors.white,
        foregroundColor: KaL_Config.KaL_MainColor,
        centerTitle: true,
      ),
      body: Container(
        color: KaL_Config.KaL_pageBgColor,
        child: Column(
          children: [
            generatorView(),
            // EJGenerator_HomePage(),
            contentListView(_numbers),
            bottomView(),
          ],
        ),
      ),
    );
  }

  Widget contentListView(var numbres) {
    return Expanded(
        child: ListView(
      padding: const EdgeInsets.all(15),
      children: [
        EJ_generaAnalyticsView(
          dataType: ViewType.type_RegularNumbersFrequency,
          Numbers: _numbers,
        ),
        EJ_generaAnalyticsView(
          dataType: ViewType.type_SkippedNumbersAnalytics,
          Numbers: _numbers,
        ),
        EJ_generaAnalyticsView(
          dataType: ViewType.type_ConsecutiveNumbersAnalytics,
          Numbers: _numbers,
        ),
        EJ_generaAnalyticsView(
          dataType: ViewType.type_SumsofNumbers,
          Numbers: _numbers,
        ),
        EJ_generaAnalyticsView(
          dataType: ViewType.type_EvenOddofNumbers,
          Numbers: _numbers,
        ),
      ],
    ));
    // return Container();
  }

  Widget generatorView() {
    double _progress = _scoredForNumbers / 100;

    return Container(
      height: 160,
      margin: EdgeInsets.all(10),
      decoration: BoxDecoration(
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.2), // 阴影颜色
            spreadRadius: 1, // 扩散半径
            blurRadius: 10, // 模糊半径
            offset: Offset(0, 1), // 阴影偏移
          ),
        ],
        borderRadius: BorderRadius.all(Radius.circular(10)),
        color: Colors.white,
      ),
      child: Stack(
        children: [
          Padding(
            padding: const EdgeInsets.only(top: 110),
            child: Container(
              height: 50,
              // width: 300,
              decoration: const BoxDecoration(
                // color: HexColor('#f6f6f6'),
                borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(10),
                    bottomRight: Radius.circular(10)),
              ),
              child: Stack(
                children: [
                  SizedBox(
                    // color: Colors.white,
                    height: 50,
                    child: LinearProgressIndicator(
                      borderRadius: const BorderRadius.only(
                          bottomLeft: Radius.circular(10),
                          bottomRight: Radius.circular(10)),
                      backgroundColor: HexColor('##F6F6F6'), // 设置进度条背景颜色
                      valueColor: AlwaysStoppedAnimation<Color>(
                          HexColor('##C9FFCF')), // 设置进度条颜色
                      value: _progress, // 设置进度值（0.0 - 1.0）
                    ),
                  ),
                  SizedBox(
                    height: 50,
                    child: Padding(
                      padding: const EdgeInsets.only(top: 10),
                      child: Row(
                        children: [
                          const SizedBox(width: 15),
                          const Text('AI scored your numbers:',
                              style: TextStyle(
                                fontSize: 13,
                                fontWeight: FontWeight.w300,
                              )),
                          const Spacer(),
                          Text(
                            _scoredForNumbers.toString(),
                            style: TextStyle(
                                fontWeight: FontWeight.w500,
                                fontSize: 13,
                                color: HexColor('#2BA471')),
                          ),
                          const SizedBox(width: 20),
                          // Image.asset('assets/sys_imgs/EJ_union.png',
                          //     width: 8.0, height: 13.0),
                          // const SizedBox(width: 15),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          Container(
            height: 120,
            width: double.infinity,
            // padding: EdgeInsets.only(left: 10, right: 10),
            decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(
                  Radius.circular(10),
                )),
            child: Column(
              children: [
                Container(
                  // color: Colors.yellow,
                  margin: const EdgeInsets.only(left: 10, right: 10, top: 10),
                  height: 30,
                  child: Row(
                    children: [
                      const Text('Generator & Analytics',
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            fontSize: 13,
                          )),
                      const Spacer(),
                      Container(
                        height: 35,
                        width: 80,
                        // alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: KaL_Config.KaL_MainColor,
                            borderRadius: const BorderRadius.all(
                                Radius.circular(35 * 0.5))),
                        child: Center(
                          child: TextButton(
                              onPressed: () {
                                debugPrint('Generate');
                                // _getgenerateRandomNumbers();
                                _generateRandomNumbers();
                              },
                              child: const Text(
                                'Generate',
                                style: TextStyle(
                                  fontSize: 11,
                                  fontWeight: FontWeight.w400,
                                  color: Colors.white,
                                ),
                              )),
                        ),
                      )
                    ],
                  ),
                ),
                KalDrawnumbersview(data: _numbersMap),
              ],
            ),
          ),
        ],
      ),
    );
  }

  ///
  Widget chooseBtn() {
    double height = 34.0;
    return Container(
      height: height,
      width: 75,
      decoration: BoxDecoration(
          color: KaL_Config.KaL_MainColor,
          borderRadius: BorderRadius.all(Radius.circular(height * 0.5))),
      child: TextButton(
          onPressed: () {
            debugPrint('choose');
            _generateRandomNumbers();
          },
          child: const Text(
            'Generate',
            style: TextStyle(
              fontSize: 11,
              fontWeight: FontWeight.w400,
              color: Colors.white,
            ),
          )),
    );
  }

  Widget bottomView() {
    String text = 'Score of the Numbers: $_scoredForNumbers';
    return Container(
      height: 45,
      color: Colors.white,
      child: Row(
        children: [
          const SizedBox(width: 15),
          Text(
            text,
            style: const TextStyle(
              fontSize: 10,
              fontWeight: FontWeight.w400,
            ),
          ),
          const Spacer(),
          OutlinedButton(
            onPressed: () {
              debugPrint('Save to Checker');
              _EJ_saveTpChecker();
            },
            style: ButtonStyle(
                backgroundColor:
                    WidgetStatePropertyAll(KaL_Config.KaL_MainColor),
                foregroundColor: WidgetStateProperty.all(Colors.white),
                side: WidgetStateProperty.all(
                    //边框
                    BorderSide(
                  color: KaL_Config.KaL_MainColor, //颜色
                  width: 1.0, //宽度
                )),
                minimumSize: const MaterialStatePropertyAll(Size(40, 35))),
            child: const Text(
              "Save to Checker",
              style: TextStyle(fontWeight: FontWeight.w400, fontSize: 13),
            ),
          ),
          const SizedBox(
            width: 15,
          ),
        ],
      ),
    );
  }
}
